package config

import (
	"fmt"

	"github.com/spf13/viper"
)

var DefaultConfig = &Config{
	Database: DatabaseConfig{
		Type:         "mysql",
		Host:         "192.168.48.250",
		Port:         3306,
		User:         "root",
		Password:     "root",
		DatabaseName: "xcloud_oauth",
		MaxIdleConns: 5,
		MaxOpenConns: 5,
	},
	Oauth: OauthConfig{
		AccessTokenLifetime:  3600,    // 1 hour
		RefreshTokenLifetime: 1209600, // 14 days
		AuthCodeLifetime:     3600,    // 1 hour
	},
	Session: SessionConfig{
		Secret:   "test_secret",
		Path:     "/",
		MaxAge:   86400 * 7, // 7 days
		HTTPOnly: true,
	},
	ServerPort:    8080,
	IsDevelopment: true,
}

// NewDefaultConfig returns *Config struct for testing purpose
func NewDefaultConfig() *Config {
	return DefaultConfig
}

// NewConfig loads configurations from config file
func NewConfig(configFile string) *Config {
	fmt.Println("NewConfig configFile:", configFile)
	if configFile != "" {
		v := viper.New()
		config := &Config{}
		v.SetConfigFile(configFile)
		if err := v.ReadInConfig(); err != nil {
			if _, ok := err.(viper.ConfigFileNotFoundError); ok {

			} else {
				panic(err)
			}
		}
		if err := v.Unmarshal(config); err != nil {
			panic(err)
		}
		return config
	}
	return NewDefaultConfig()
}
